﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Eshouse.Entity;
using System.Data;

namespace Eshouse.Bll
{
    public class RoleAccess
    {

        public static DataTable GetRoleTable()
        {
            
            string strSql = "select roleid,rolename from sysrole";
            DatabaseHelper db = new DatabaseHelper();
            return db.ExecuteDataTable(strSql);      
            

        }
        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="item">用户选择的菜单</param>
        /// <returns></returns>
        public static string SaveRoleItem(string item, string roleName)
        {        
            DatabaseHelper db = new DatabaseHelper();
            string res = "1";           
            string sqlUpdate = "update sysrole set sysmodel='" + item + "' where rolename='" + roleName + "'";            
            if (db.ExecuteNonQuery(sqlUpdate) == -1)
                res = "0";
            return res;

        }
        /// <summary>
        /// 加载树权限菜单
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public static string LoadRoleTree(string roleName)
        {
            string res = "";
            StringBuilder resultStr = new StringBuilder();
            DatabaseHelper db = new DatabaseHelper();
            string sqlSelModel = "select sysmodel from sysrole where rolename='" + roleName + "'";
            //string sqlselMenu = "select id,menuid,fatherid,menuname,menuurl from menu";
            //DataTable menu = db.ExecuteDataTable(sqlselMenu);
            DataTable menu = new DataTable();
            DataSet ds = new DataSet();
            ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath("~/xmlConfig/menuConfig.xml"));
            menu = ds.Tables[0];

            DataRow[] modelID = menu.Select("nodetype='0'");
            string sysModel = "";
            object o = db.ExecuteScalar(sqlSelModel);
            if (o == null)
                return "";
            sysModel = o.ToString();
            Dictionary<string, string> modelKey = new Dictionary<string, string>();
            if (sysModel == "")
            {
                resultStr.Append("[");
                for (int i = 0; i < modelID.Length; i++)
                {
                    DataRow row = modelID[i];
                    resultStr.Append("{");
                    resultStr.Append(string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"state\": \"closed\",\"addr\": \"{2}\"", row["menuid"], row["menuname"].ToString(), row["menuurl"].ToString()));
                    resultStr.Append(SubTree(row["menuid"].ToString(), menu, modelKey));
                    resultStr.Append("}");
                    if (i < modelID.Length - 1)
                        resultStr.Append(",");
                }
                resultStr.Append("]");
            }
            else  ///根据已经设置好的权限读取菜单
            {
                
                string[] models = sysModel.Split(',');
                for (int i = 0; i < models.Length; i++)
                {
                    if (models[i] != "")
                    {
                        if (!modelKey.ContainsKey(models[i]))
                            modelKey.Add(models[i], "");
                    }
                }
                resultStr.Append("[");
                string ischk = "false";
                for (int i = 0; i < modelID.Length; i++)
                {
                    DataRow row = modelID[i];
                    if (modelKey.ContainsKey(row["menuid"].ToString()))
                    {
                        ischk = "true";
                    }
                    else {
                        ischk = "false";
                    }
                    resultStr.Append("{");
                    resultStr.Append(string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"state\": \"closed\",\"addr\": \"{2}\",\"checked\":{3}", row["menuid"], row["menuname"].ToString(), row["menuurl"].ToString(), ischk));
                    resultStr.Append(SubTree(row["menuid"].ToString(), menu, modelKey));
                    resultStr.Append("}");
                    if (i < modelID.Length - 1)
                        resultStr.Append(",");

                }
                resultStr.Append("]");
            }
            res = resultStr.ToString();
            return res;

        }
        /// <summary>
        /// 递归每一个模块的所有子菜单
        /// </summary>
        /// <param name="menuid">模块的id</param>
        /// <param name="menu">所有菜单表</param>
        /// <returns>string</returns>
        private static string SubTree(string menuid, DataTable menu, Dictionary<string, string> modelKey)
        {
            StringBuilder resultStr = new StringBuilder();
            resultStr.Append("");
            DataRow[] rows = menu.Select("fatherid='" + menuid + "'");
            if (rows.Length > 0)
            {
                string ischk = "false";
                resultStr.Append(",\"children\":[");
                string menuidtmp = "";
                for (int i = 0; i < rows.Length; i++)
                {
                    DataRow row = rows[i];
                    if (modelKey.ContainsKey(row["menuid"].ToString()))
                    {
                        ischk = "true";
                    }
                    else
                    {
                        ischk = "false";
                    }
                    resultStr.Append("{");
                    menuidtmp = row["menuid"].ToString();
                    if (menu.Select("fatherid='" + menuidtmp + "'").Length > 0)
                    {
                        resultStr.Append(string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"state\": \"closed\",\"addr\": \"{2}\",\"checked\":{3}", menuidtmp, row["menuname"].ToString(), row["menuurl"].ToString(), ischk));
                    }
                    else
                    {
                        resultStr.Append(string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"state\": \"closed\",\"iconCls\": \"tree_file\",\"addr\": \"{2}\",\"checked\":{3}", menuidtmp, row["menuname"].ToString(), row["menuurl"].ToString(), ischk));
                    }
                    resultStr.Append(SubTree(row["menuid"].ToString(), menu, modelKey));
                    resultStr.Append("}");
                    if (i < rows.Length - 1)
                        resultStr.Append(",");
                }
                resultStr.Append("]");
            }
            return resultStr.ToString();
        }
        public static string GetRoleNameByID(string id)
        {
            string roleName = "";
            string sql = "select rolename from SysRole where roleid=" + id;
            DatabaseHelper db = new DatabaseHelper();
            object o = db.ExecuteScalar(sql);
            roleName = o == null ? "无法获取信息" : o.ToString();
            return roleName;
        }

        public static bool VerifyRoleName(string roleName)
        {
            bool isExist = false;
            DatabaseHelper dbhelper = new DatabaseHelper();
            string strSql = string.Format("select roleid from SysRole where rolename ='{0}'", roleName);
            object o = dbhelper.ExecuteScalar(strSql);
            if (o != null)
                isExist = true;
            return isExist;

        }
        public static bool InsertRole(string roleName)
        {
            bool seccess = true;
            CRC32Primarykey crc = new CRC32Primarykey();
            DateTime now = DateTime.Now;
            int roleId = crc.createIntID("role" + now.ToString() + now.Millisecond.ToString());
            string strSql = string.Format("insert SysRole(roleID,roleName) values ({0},'{1}')", roleId, roleName);
            DatabaseHelper db = new DatabaseHelper();
            if (db.ExecuteNonQuery(strSql) <= 0)
                seccess = false;
            return seccess;
        }
        public static DataTable GetRoleDataTabel()
        {
            DataTable dt = null;

            string strSql = "select * from SysRole";
            DatabaseHelper db = new DatabaseHelper();
            dt = db.ExecuteDataTable(strSql);
            return dt;

        }
        public static bool DeleteRole(string id)
        {
            NHibernateHelper Nhelper = new NHibernateHelper();
            ISession session = Nhelper.GetSession();
            SysRole role = new SysRole();
            role.Id =Convert.ToInt32(id);
            bool secess = true;
            try
            {
                session.Delete(role);
                session.Flush();
            }
            catch (Exception ex)
            {
                logRecord.RecordErr("删除角色错误", ex);
                return false;
            }

            //string strSql = "delete from SysRole where roleID=@id";
            //DatabaseHelper db = new DatabaseHelper();
            //db.AddParameter("@id", id);
            //if (db.ExecuteNonQuery(strSql) <= 0)
            //    secess = false;
            return secess;
        }
        public static string GetRoleJson()
        {

            DataTable dt = GetRoleDataTabel();
            if (dt == null)
                return "";
            int rowCount = dt.Rows.Count;
            try
            {
                dt.Columns.Remove("sysmodel");
            }
            catch (Exception ex)
            {
                logRecord.RecordErr("移除sysmodel列时发生异常", ex);
            }
            return publicComm.GetJsonString(dt, rowCount);

        }
    }
}
